package Controller;


import Util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Class self = this.getClass();

        String method = request.getParameter("method");

        try {

            Method method1 = self.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);

            String invoke = (String) method1.invoke(this, request, response);


            if(invoke!=null){
                if(invoke.startsWith(Constants.FORWARD)){
                    String path = invoke.substring(invoke.indexOf(":") + 1);

                    request.getRequestDispatcher(path).forward(request,response);
                }else if(invoke.startsWith(Constants.REDIRECT)){
                    String path = invoke.substring(invoke.indexOf(":") + 1);

                    response.sendRedirect(request.getContextPath()+path);
                }else{
                    response.getWriter().println(invoke);
                }
            }

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
